import { InputValueType } from '@app-nextmesh/types';
import {
  Box,
  Button,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
} from '@mui/material';
import { isArray, isNumber } from 'lodash';
import { useEffect, useState } from 'react';
import ErrorTips from './ErrorTips';
import UnitSelect from './UnitSelect';
import ValueInput from './ValueInput';
import { IBaseProps } from './types';

/** formFormat 格式示例：
   {
    "Type": "tabular",
    "Overclosure": {
        "Unit": "mm",
        "Default": [0, 1]
      },
      "Pressure": {
        "Unit": ["MPa"],
        "Default": [0, 10000]
      }
    }
 * form 格式示例：
   {
      "Type": "tabular",
      "Value": {
        "Overclosure": {
          "Unit": "mm",
          "Value": [0, 1]
        },
        "Pressure": {
          "Unit": "MPa",
          "Value": [0, 10000]
        }
      }
    }
*/
interface IProps extends IBaseProps<object> {
  formFormat: object; //
}
export default function Tabular({
  formFormat,
  disabled,
  value: initValue,
  onChange: onInputChange,
}: IProps) {
  const [value, setValue] = useState<object>();
  useEffect(() => {
    setValue(initValue);
  }, [initValue]);
  if (!value) {
    return <></>;
  }

  const handleInputChange = (
    name: string,
    index: number,
    v: InputValueType,
  ) => {
    // 更新值
    const nameValue = { ...value[name] };
    nameValue.Value[index] = v;
    const newValue = { ...value, [name]: nameValue };
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleUnitChange = (name: string, unit: string) => {
    // 更新单位
    // 更新值
    const nameValue = { ...value[name] };
    nameValue.Unit = unit;
    const newValue = { ...value, [name]: nameValue };
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleDelete = (rowIndex: number) => {
    const newValue = { ...value };
    const names = Object.keys(newValue);
    // 循环删除每一列的
    names.forEach((name) => newValue[name].Value.splice(rowIndex, 1));
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleAdd = () => {
    const newValue = { ...value };
    const names = Object.keys(newValue);
    names.forEach((name) => newValue[name].Value.push(0)); // TODO 根据类型设置添加的默认值
    setValue(newValue);
    onInputChange(newValue);
  };
  // 由formFormat和value 生成table可用的数据
  // 生成table头
  const columns = Object.keys(value);
  // 获取每列的单位
  const units = columns.map((column) => {
    const unit = formFormat[column]['Unit'];
    return unit;
  });
  const rows = [];
  // 取其中一个最短Value的长度，进行循环生成table数据
  let minLength = 100;
  columns.forEach((column) => {
    const theOne = value[column];
    if (theOne && isArray(theOne.Value)) {
      const length = theOne.Value.length;
      minLength = length < minLength ? length : minLength;
    }
  });
  for (let index = 0; index < minLength; index++) {
    const item = {};
    columns.forEach((column) => {
      item[column] = { Value: value[column].Value[index] };
    });
    rows.push(item);
  }
  const TableHeadRow = ({
    columns,
    units,
    formValue,
  }: {
    columns: string[];
    units: any[];
    formValue: any;
  }) => {
    return (
      <TableRow>
        {columns.map((column, index) => (
          <TableCell key={index}>
            <Stack>
              <div style={{ textAlign: 'center' }}>{column}</div>
              <UnitSelect
                value={formValue[column]['Unit']}
                units={units[index]}
                onChange={(value) => handleUnitChange(column, value as string)}
              />
            </Stack>
          </TableCell>
        ))}
        <TableCell key={columns.length}>
          <div style={{ textAlign: 'center' }}>操作</div>
        </TableCell>
      </TableRow>
    );
  };
  const TableBodyRows = ({
    rows,
    columns,
  }: {
    rows: any[];
    columns: string[];
  }) => {
    const numberType = 'double';
    return (
      <>
        {rows.map((row, rowIndex) => (
          <TableRow
            key={rowIndex}
            sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
            {columns.map((column, colIndex) => (
              <TableCell key={colIndex}>
                {isNumber(row[column].Value) ? (
                  <ValueInput
                    type={numberType}
                    value={row[column].Value}
                    disabled={disabled}
                    onChange={(value) =>
                      handleInputChange(column, rowIndex, value as number)
                    }
                  />
                ) : (
                  <ErrorTips>格式错误，必须是一个数字</ErrorTips>
                )}
              </TableCell>
            ))}
            <TableCell key={columns.length}>
              <Button
                disabled={disabled}
                variant='text'
                onClick={() => handleDelete(rowIndex)}>
                删除
              </Button>
            </TableCell>
          </TableRow>
        ))}
      </>
    );
  };
  return (
    <>
      <TableContainer style={{ maxHeight: '300px' }}>
        <Table sx={{ minWidth: 100 }}>
          <TableHead>
            <TableHeadRow
              columns={columns}
              units={units}
              formValue={value}
            />
          </TableHead>
          <TableBody>
            <TableBodyRows
              rows={rows}
              columns={columns}
            />
          </TableBody>
        </Table>
      </TableContainer>
      <Box
        display='flex'
        justifyContent='center'>
        <Button
          style={{ width: '100%', fontSize: '18px' }}
          variant='text'
          onClick={handleAdd}>
          +
        </Button>
      </Box>
    </>
  );
}
